package cn.xdwanj.ask.controller;

import cn.xdwanj.ask.entity.User;
import cn.xdwanj.ask.service.UserService;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.swagger.v3.oas.annotations.Parameter;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.Map;

/**
 * @author xdwanj
 */
@Slf4j
@RestController
@RequiredArgsConstructor
@RequestMapping("/user")
public class UserController {

    private final ObjectMapper objectMapper;
    private final UserService userService;

    @RequestMapping("/login.do")
    public int login(String user, String pass,
                     @Parameter(hidden = true)
                     HttpSession session) {
        var userList = userService.lambdaQuery()
            .eq(User::getUsername, user)
            .eq(User::getPassword, pass)
            .list();

        if (userList.size() != 0) {
            session.setAttribute("username", user);
            session.setAttribute("userid", userList.get(0).getId());
            session.setAttribute("islogin", 1);
            return 1;
        } else {
            return 0;
        }

    }

    @RequestMapping("/exit.do")
    public int exit(@Parameter(hidden = true) HttpSession session) {
        session.invalidate();
        return 1;
    }

    @RequestMapping("/loginInfo.do")
    public String loginInfo(
        // @Parameter(hidden = true)
        // @SessionAttribute("islogin") Integer isLogin,
        @Parameter(hidden = true) HttpSession session
    ) throws JsonProcessingException {
        Integer isLogin = (Integer) session.getAttribute("islogin");
        if (isLogin == null || isLogin == 0) {
            return "0";
        }

        var loginInfo = Map.of(
            "username", session.getAttribute("username")
        );

        return objectMapper.writeValueAsString(loginInfo);
    }
}
